﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using NDK.Utils;
using DevComponents.DotNetBar.Keyboard;
using NDK.Module.BLL;
using NDK.Module.Model;
using NDK.Module.DAL;
using System.Threading;
using System.Diagnostics;
using System.Text;
using BZ.Logger;
using NDK.Motion.BLL;


using NDK.Module.StationLogic;
using NDK.Motion.Sys;
using System.IO;
using NDK.Motion.MachineManager;
using NDK.Motion.Frm;
using VisionPlatform;
using static NDK.Module.Model.Common;
using System.Net;
using BZVision;

namespace NDK.Frm
{

    public partial class Frm_Main : Form
    {
        #region fileds/properties
        private static log4net.ILog visionLogger = log4net.LogManager.GetLogger("VisionLogger");

        //public MachineModel machine;

        const int ON = 1;
        const int OFF = 0;
        #endregion fileds/properties

        #region 解决闪烁问题
        /// <summary>
        /// 解决闪烁问题
        /// </summary>
        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        CreateParams cp = base.CreateParams;
        //        cp.ExStyle |= 0x02000000;
        //        return cp;
        //    }
        //}
        #endregion

        #region 窗体对象实例，单例模式,保证整个工程只有一个实例
        private static Frm_Main _instance;
        private static readonly object singletonLock = new object();
        public static Frm_Main Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new Frm_Main();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion

        #region 线程定义
        public Thread thread_TriColorLamp = null; //三色灯线程
        public Thread thread_AxisStatus = null; //监控轴报警线程
        public Thread Thread_Home = null; //机台初始化线程
        public Thread Thread_ScanButton = null;////扫描机台按钮、光幕线程

        public Thread Thread_MonitorEMGSignal = null;//监控急停信号
        public Thread Thread_MonitorDoorGSignal = null;//监控急停信号

        public Thread Thread_UserOptionCheckBFMessage = null;//监控系统是否闲置

        public Thread Thread_SaveImage = null;//监控系统是否闲置

        public Thread Thread_PointCheck = null;
        #endregion

        private Frm_Main()
        {
            InitializeComponent();
            AppendUiLog = GlobleLoggerConfiguration.Config();
            // machine = MachineFactory.Instance.CreateMachine();
            //AppDomain.CurrentDomain.SetData("machine", machine);

            ProTypeListItemsInit();
            //tscb_ProTypeList.SelectedIndexChanged += new System.EventHandler(this.tscb_ProTypeList_SelectedIndexChanged);

            #region 五分钟没有鼠标键盘响应就上锁(指纹锁权限要用的)
            msg = new UserOptionCheckBFMessage();
            Application.AddMessageFilter(msg);
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            #endregion

            #region 上传苹果MacMini通信回调函数
            AsyncClient_MacMini.Completed += new Action<System.Net.Sockets.TcpClient, AsyncTcpIpUtils.EnSocketAction>(CompletedFromMacMini);
            AsyncClient_MacMini.Received += new Action<string, string>(ReceivedFromMacMini);
            #endregion

            
            #region 加载视觉框架
            try
            {

                Vision.Intial();

                //VisionManager.Event.LogDebug += Event_LogDebug;
                //VisionManager.Event.LogError += Event_LogError;
                //VisionManager.Event.LogFatal += Event_LogFatal;
                //VisionManager.Event.LogInfo += Event_LogInfo;
                //VisionManager.Event.LogWarn += Event_LogWarn;
                //VisionManager.Event.LogModify += Event_LogModify;
                VisionManager.Event.GetAuthority += Event_GetAuthority;

            }
            catch (Exception ex)
            {

            }

            #endregion

            #region 初始化Mind Vision相机
            PublicMethod.UpdateRuningData();
            Frm_InitItemStatu.Instance.UpdateStep(65, "初始化MindVision相机", true);
            if (PublicMethod.MindVision() == false)
            {
                Frm_InitItemStatu.Instance.UpdateStep(70, "初始化MindVision相机失败", false);
                AppendUiLog.Log("相机加载失败 ", LogType.Error);
            }
            else
            {
                Frm_InitItemStatu.Instance.UpdateStep(70, "初始化MindVision相机成功", true);
                AppendUiLog.Log("相机加载成功 ", LogType.Info);
            }
            #endregion
            #region 加载视觉框架
            try
            {


                var ret = PublicMethod.LoadSlp(CurProType);
                if (ret)
                    Frm_InitItemStatu.Instance.UpdateStep(71, "加载算法Slp路径成功", true);
                else
                    Frm_InitItemStatu.Instance.UpdateStep(70, "加载算法Slp路径失败", false);
            }
            catch (Exception ex)
            {

            }

            #endregion

        }

        public void ReceivedFromMacMini(string key, string msg)
        {
            string Recv = string.Empty;
            AsyncRcvMsgFromMacMini = "";

            Recv = msg;
            msg = "";

            //Common.AsyncRcvMsgFromMacMini = Recv.Split('@')[0]; //Recv.Substring(0,3);

            if (Recv.Split('@')[0].Equals("ok"))
            {
                if (Recv.Split('@')[1].Contains("success"))
                {
                    AsyncRcvMsgFromMacMini = "MacMiniOk";
                }
                else
                {
                    AsyncRcvMsgFromMacMini = "MacMiniOkElse";
                }
            }
            else if (Recv.Split('@')[0].Equals("ng"))
            {
                AsyncRcvMsgFromMacMini = "MacMiniNg";
            }
            else if (Recv.Split('@')[0].Equals("err"))
            {
                if (Recv.Split('@')[1].Contains("please create one with 'start' command first"))
                {
                    AsyncRcvMsgFromMacMini = "MacMiniErrWithoutStart";
                }
                else
                {
                    AsyncRcvMsgFromMacMini = "MacMiniErr";
                }
            }

            AppendUiLog.Log("RcvMacMini: " + Recv, LogType.Alert);

            try
            {
                WriteLogToTxt(Recv + "\r\n");
            }
            catch (Exception EX)
            {
                AppendUiLog.Log("接收写入数据出错" + EX.ToString(), LogType.Error);
            }
        }

        public void CompletedFromMacMini(System.Net.Sockets.TcpClient c, AsyncTcpIpUtils.EnSocketAction enAction)
        {
            try
            {
                IPEndPoint iep = c.Client.RemoteEndPoint as IPEndPoint;
                string key = string.Format("{0}:{1}", iep.Address.ToString(), iep.Port);
                switch (enAction)
                {
                    case AsyncTcpIpUtils.EnSocketAction.Connect:
                        break;
                    case AsyncTcpIpUtils.EnSocketAction.SendMsg:
                        break;
                    case AsyncTcpIpUtils.EnSocketAction.Close:
                        MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                        button1.BackColor = Color.Red;

                        AppendUiLog.Log("与苹果MacMini断开连接，请检查", LogType.Alert);
                        if (DialogResult.OK == MessageBox.Show("监测到上传MacMini断开连接，请确认MacMini是否正常！"))
                        {
                            try
                            {
                                AsyncClient_MacMini.Disconnect();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("断开MacMini连接异常" + ex.ToString());
                            }

                            MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                        }
                        else
                        {
                            AsyncClient_MacMini.Disconnect();
                            MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                AppendUiLog.Log(ex.ToString(), LogType.Error);
            }
        }

        private static void WriteLogToTxt(string strLog)
        {

            String System_Now_Time = null;
            String File_Create_Time = null;

            System_Now_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff");//HH:mm:ss
            File_Create_Time = DateTime.Now.ToString("yyyyMMdd");
            string logDocument = File_Create_Time + ".txt";

            string str = Process.GetCurrentProcess().MainModule.FileName;
            string logFilePath = str.Substring(0, str.LastIndexOf("\\")) + "\\RecvInfoLogMacMini";
            if (!Directory.Exists(logFilePath))
            {
                Directory.CreateDirectory(logFilePath);
            }
            logFilePath = logFilePath + "//" + logDocument;
            FileStream fs = new FileStream(logFilePath, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            sw.WriteLine(System_Now_Time + ":   " + strLog);
            sw.Flush();
            sw.Close();
            fs.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            #region UI
            //修改主窗体的样式
            StyleUtils.MainFormStyle(this);
            //修改子窗体的样式
            StyleUtils.SetMdiStyle(this, Frm_Home.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Setting.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Login.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Statistics.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Alarm2.Instance, 0, tlp_Menu.Height);

            tlp_FrmContainer.Controls.Add(Frm_Home.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Setting.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Login.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Statistics.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Alarm2.Instance, 0, 2);

            Frm_Home.Instance.Dock = DockStyle.Fill;
            Frm_Setting.Instance.Dock = DockStyle.Fill;
            Frm_Login.Instance.Dock = DockStyle.Fill;
            Frm_Statistics.Instance.Dock = DockStyle.Fill;
            Frm_Alarm2.Instance.Dock = DockStyle.Fill;
            toolStripComboBox1.Items.Clear();
            if (CurProType == "Product")
            {
                whichBlock = -1;
                toolStripComboBox1.Items.Add("-1");
                toolStripComboBox1.SelectedItem = "-1";
                toolStripComboBox1.Enabled = false;
            }
            else
            {
                whichBlock = 0;
                //toolStripComboBox1.SelectedItem = "0";
                toolStripComboBox1.Items.Add("0");
                toolStripComboBox1.Items.Add("1");
                toolStripComboBox1.Items.Add("2");
                toolStripComboBox1.Enabled = true;
            }
            Frm_Home.Instance.Show();

            #endregion

            ucBtnExt_MachineInfo.BtnText = ProjectName;
            this.WindowState = FormWindowState.Maximized;

            UpdateMeasureItemsEnable += UpdateProTypeMeasureItemsEnable;
            LoadingMove.Instance.UpdateStartOnceEvent += new delegateUpdateStartOnce(UpdateStartOnce);

            //三色灯线程开启
            Instance.thread_TriColorLamp = new Thread(PublicMethod.ThreadMethod_TriColorLamp);
            Instance.thread_TriColorLamp.IsBackground = true;
            Instance.thread_TriColorLamp.Start();

#if true

            //监控轴报警
            Instance.thread_AxisStatus = new Thread(PublicMethod.ThreadMethod_AxisStatus);
            Instance.thread_AxisStatus.IsBackground = true;
            Instance.thread_AxisStatus.Start();

            //监控EMG急停信号
            Instance.Thread_MonitorEMGSignal = new Thread(PublicMethod.ThreadMethod_EMGStatus);
            Instance.Thread_MonitorEMGSignal.IsBackground = true;
            Instance.Thread_MonitorEMGSignal.Start();

            //监控门信号
            Instance.Thread_MonitorDoorGSignal = new Thread(PublicMethod.ThreadMethod_DoorStatus);
            Instance.Thread_MonitorDoorGSignal.IsBackground = true;
            Instance.Thread_MonitorDoorGSignal.Start();

            //复位线程开启
            Instance.Thread_Home = new Thread(PublicMethod.ThreadMethod_Home);
            Instance.Thread_Home.IsBackground = true;
            Instance.Thread_Home.Start();


            //按钮、光幕
            Instance.Thread_ScanButton = new Thread(PublicMethod.ThreadMethod_ScanButton);
            Instance.Thread_ScanButton.IsBackground = true;
            Instance.Thread_ScanButton.Start();

            //5分钟系统闲置加更改登录状态
            Instance.Thread_UserOptionCheckBFMessage = new Thread(background_DoWork);
            Instance.Thread_UserOptionCheckBFMessage.IsBackground = true;
            Instance.Thread_UserOptionCheckBFMessage.Start();


            Instance.Thread_ScanButton = new Thread(PublicMethod.ThreadMethod_PLCHeart);
            Instance.Thread_ScanButton.IsBackground = true;
            Instance.Thread_ScanButton.Start();

            Instance.Thread_ScanButton = new Thread(PublicMethod.ThreadMethod_HeartFormPLC);
            Instance.Thread_ScanButton.IsBackground = true;
            Instance.Thread_ScanButton.Start();

            Instance.Thread_PointCheck = new Thread(PublicMethod.ThreadMethod_PointCheck);
            Instance.Thread_PointCheck.IsBackground = true;
            Instance.Thread_PointCheck.Start();
#endif

            #region 连接苹果MacMini服务器
            bool bConnectSelfOK = true;
            try
            {
                if (isUploadApple == true)
                {
                    bConnectSelfOK = AsyncClient_MacMini.ConnectAsync("169.254.1.10", 1111);

                    if (!bConnectSelfOK)
                    {
                        button1.BackColor = Color.Red;
                        AppendUiLog.Log("连接MacMini失败！", LogType.Error);
                    }
                    else
                    {
                        if (isUploadApple == true)
                        {
                            button1.BackColor = Color.PaleGreen;
                        }
                        else
                        {
                            button1.BackColor = Color.Yellow;
                        }
                        AppendUiLog.Log("连接MacMini成功！", LogType.Alert);
                    }
                }
                else
                {
                    button1.BackColor = Color.Yellow;
                    AppendUiLog.Log("未打开MacMini连接！", LogType.Alert);
                }
            }
            catch (Exception ex)
            {
                button1.BackColor = Color.Red;
                AppendUiLog.Log("连接MacMini异常！" + ex.ToString(), LogType.Error);
            }
            #endregion

            #region 初始化视觉框架变量
            VisionManager.Engine eng = null;
            eng = new VisionManager.Engine("InitialVariable");
            eng.ActionFun();
            #endregion


            if (b硬件初始化成功 == true && bConnectSelfOK == true)//Common.isFingerPrintInitialed
            {
                Thread.Sleep(2000);
                AppendUiLog.Log("设备初始化成功，请复位", LogType.Info);
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Initialized;
            }
            else
            {
                Thread.Sleep(2000);
                AppendUiLog.Log("设备初始化失败，请检查", LogType.Error);
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Unknown;
            }

        }

        private void MachineStatusManager_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            this.lbl_Status.Text = e.PropertyName;
        }
        public void Event_LogModify(string str)
        {
            AppendUiLog.Log(str, LogType.Alert);
            visionLogger.Warn(str);
        }

        public void Event_LogWarn(string str)
        {
            AppendUiLog.Log(str, LogType.Alert);
            visionLogger.Warn(str);
        }

        public void Event_LogInfo(string str)
        {
            AppendUiLog.Log(str, LogType.Info);
            visionLogger.Info(str);
        }

        public void Event_LogFatal(string str)
        {
            AppendUiLog.Log(str, LogType.Error);
            visionLogger.Fatal(str);
        }

        public void Event_LogError(string str)
        {
            AppendUiLog.Log(str, LogType.Error);
            visionLogger.Error(str);
        }

        public void Event_LogDebug(string str)
        {
            AppendUiLog.Log(str, LogType.Info);
            visionLogger.Debug(str);
        }
        public Authority Event_GetAuthority()
        {
            switch (Common.Authority)
            {
                case "Operator":
                case "BZ":
                case "EN":
                case "Battery QM":
                //return Authority.ProdocutOp;
                case "Apple":
                    return VisionPlatform.Authority.ProdouctEng;
                default:
                    return VisionPlatform.Authority.ProdouctEng;//暂时有算法权限
            }
        }

        #region 快捷键
        string LogKey = "000";

        /// <summary>
        /// 按ESC退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_ESCKeyPress(object sender, KeyEventArgs e)
        {
            if (e.Shift && e.Control && e.KeyCode == Keys.B)//调用Block点检
            {
                if (isPointCheck)
                {
                    isPointCheck = false;
                    AppendUiLog.Log("气缸信号RunB00000");
                }
                else
                {
                    isPointCheck = true;
                    AppendUiLog.Log("气缸信号RunB11111");
                }
            }
            if (e.Shift && e.Control && e.KeyCode == Keys.G)//调用GRR点检
            {
                if (isGRRPointCheck)
                {
                    isGRRPointCheck = false;
                    AppendUiLog.Log("气缸信号RunR00000");
                }
                else
                {
                    Random r;
                    isGRRPointCheck = true;
                    //生成GRR范围
                    MeasureSizeServices measureSizeService = new MeasureSizeServices();
                    List<MeasureSize> measureSizeList = measureSizeService.GetAllByProjectNameAndTurnNum(ProjectName, 0);
                    for (int i = 0; i < measureSizeList.Count; i++)
                    {
                        if (measureSizeList[i].IsShow == false || measureSizeList[i].IsJudging == false)
                        {
                            continue;
                        }
                        r = new Random((int)(Jugement.GetRandomSeed()));
                        double L = double.Parse(GRRRangeTable.Rows[2][measureSizeList[i].SizeName].ToString());//读取GRR点检表中的范围，生成一个随机数
                        double U = double.Parse(GRRRangeTable.Rows[0][measureSizeList[i].SizeName].ToString());
                        double Tolerance = double.Parse(GRRRangeTable.Rows[1][measureSizeList[i].SizeName].ToString());//读取GRR点检表中的公差带

                        double range = Tolerance * (r.NextDouble() * (U - L) + L);
                        //Common.GRRRangeTable.Rows[3][measureSizeList[i].SizeName] = range.ToString("0.000");
                    }
                    //FileUtils.SaveCSV(Common.GRRRangeTable, Common.pointCheckPath + @"\grrRange.csv");
                    AppendUiLog.Log("气缸信号RunR11111");
                }
            }
        }
        #endregion 按ESC键，退出程序

        #region 主界面按钮点击事件
        private void ucBtnImg_Home_BtnClick(object sender, EventArgs e)
        {
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Home.Instance.Show();
            Frm_Statistics.Instance.Hide();
            Frm_Alarm2.Instance.Hide();
        }

        private void ucBtnImg_Setting_BtnClick(object sender, EventArgs e)
        {
            if (username == "Apple" || username == "superadmin"
                  || username == "EN"
                  || username == "Battery QM")
            {
                Frm_Home.Instance.Hide();
                Frm_Login.Instance.Hide();
                Frm_Setting.Instance.Show();
                Frm_Statistics.Instance.Hide();
                Frm_Alarm2.Instance.Hide();
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (username == "Battery QM")
            {
                //Frm_Setting.Instance.sti_TrackSetting.Visible = true;
                //Frm_Setting.Instance.superTabItem2.Visible = true;
                //Frm_Setting.Instance.superTabItem4.Visible = true;
                //Frm_Setting.Instance.superTabItem1.Visible = true;
                //Frm_Setting.Instance.tab_SizeConfig.Visible = true;
                //Frm_Setting.Instance.superTabItem8.Visible = true;
                //Frm_Setting.Instance.dgv_Home.Enabled = false;
                //Frm_Setting.Instance.dgv_SizeConfig.Enabled = false;
            }
            else if (username == "EN" || username == "Apple" || username == "superadmin")
            {
                //Frm_Setting.Instance.sti_TrackSetting.Visible = true;
                //Frm_Setting.Instance.superTabItem2.Visible = true;
                //Frm_Setting.Instance.superTabItem4.Visible = true;
                //Frm_Setting.Instance.superTabItem1.Visible = true;
                //Frm_Setting.Instance.tab_SizeConfig.Visible = true;
                //Frm_Setting.Instance.superTabItem8.Visible = true;
                //Frm_Setting.Instance.dgv_Home.Enabled = true;
                //Frm_Setting.Instance.dgv_SizeConfig.Enabled = true;
            }
        }

        private void ucBtnImg_Vision_BtnClick(object sender, EventArgs e)
        {
            if (username == "EN" || username == "Apple" || username == "superadmin")
            {
                if (!Frm_VisionDebug.Instance.Visible)
                {
                    Frm_VisionDebug.Instance.Show(this);
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void ucBtnImg_Statistics_BtnClick(object sender, EventArgs e)
        {
            return;
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Home.Instance.Hide();
            Frm_Statistics.Instance.Show();
            isHomeFormShow = false;
            isSettingFormShow = false;
            isStatisticsFromShow = true;
            isVisionFromshow = false;
            isLoginFormshow = false;
            isAlarmFromshow = false;
        }

        private void ucBtnImg_Alarm_BtnClick(object sender, EventArgs e)
        {
            Frm_Alarm2.Instance.dtp_StartDate.Text = DateTime.Now.AddDays(-1).ToString();
            Frm_Alarm2.Instance.dtp_EndDate.Text = DateTime.Now.ToString();
            Frm_Alarm2.Instance.dtp_StartTime.Text = DateTime.Now.ToString();
            Frm_Alarm2.Instance.dtp_EndTime.Text = DateTime.Now.ToString();

            Frm_Home.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Setting.Instance.Hide();
            Frm_Statistics.Instance.Hide();
            Frm_Alarm2.Instance.Show();

            isHomeFormShow = false;
            isSettingFormShow = false;
            isStatisticsFromShow = false;
            isVisionFromshow = false;
            isLoginFormshow = false;
            isAlarmFromshow = true;
        }

        private void ucBtnImg_Start_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Start();
        }

        private void ucBtnImg_Pause_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Pause();
        }
        private void ucBtnImg_Homing_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Intial();
        }
        private void ucBtnImg_Stop_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Stop();
        }

        private void ucBtnImg_OpenFile_BtnClick(object sender, EventArgs e)
        {
            if (FileUtils.IsExistDirectory(dataSavePath))
            {
                Process.Start(dataSavePath);
            }
            else
            {
                FileUtils.CreateDirectory(dataSavePath);
                Process.Start(dataSavePath);
            }
        }

        private void ucBtnImg_OpenPicture_BtnClick(object sender, EventArgs e)
        {
            if (FileUtils.IsExistDirectory(picSavePath))
            {
                Process.Start(picSavePath);
            }
            else
            {
                FileUtils.CreateDirectory(picSavePath);
                Process.Start(picSavePath);
            }
        }

        private void ucBtnImg_Login_BtnClick(object sender, EventArgs e)
        {
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Show();
            Frm_Home.Instance.Hide();
            Frm_Statistics.Instance.Hide();
        }

        private void ucBtnExt_MachineInfo_BtnClick(object sender, EventArgs e)
        {
            Dlg_Version.Instance.ShowDialog(this);
        }

        private void btn_PointCheckReview_BtnClick(object sender, EventArgs e)
        {
            Dlg_PointCheck pointCheckDlg = new Dlg_PointCheck();
            pointCheckDlg.Show();
        }
        #endregion

        #region 锁屏
        private void btn_LockScreen_Click(object sender, EventArgs e)
        {
            Frm_LockScreen.Instance.ShowDialog(this);
        }
        #endregion 锁屏

        #region 软键盘
        private void btn_TouchKeyBoard_Click(object sender, EventArgs e)
        {
            this.touchKeyboard1.ShowKeyboard(this, TouchKeyboardStyle.Inline);
        }
        #endregion

        #region 指纹锁
        public void RegiserLockProcess()
        {
            if (backgroundWorker1.IsBusy)
                return;
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (msg.RegiserLockFlag)
            {
                msg.nUserOptionsCount++;
                if (msg.nUserOptionsCount > 5)
                {
                    //五分钟不动鼠标键盘时的执行操作函数。
                    msg.nUserOptionsCount = 0;

                    Common.Authority = "OP";
                    fingerPrintAuthority = "";

                    Frm_Login.Instance.SetPassCode();

                    string halconExamples = FileUtils.GetAppDirectory();

                    isFileSetPassCode = true;
                    ProcedurePath = halconExamples + @"\hdevengine\procedures.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}";

                    break;
                }

                Thread.Sleep(60000);
            }
        }

        private void background_DoWork()
        {
            while (msg.RegiserLockFlag)
            {
                msg.nUserOptionsCount++;
                if (msg.nUserOptionsCount > 1000)
                {
                    //五分钟不动鼠标键盘时的执行操作函数。
                    msg.nUserOptionsCount = 0;

                    Common.Authority = "OP";
                    username = "Operator";
                    Frm_Setting.Instance.Hide();
                    Frm_Login.Instance.Hide();
                    Frm_Home.Instance.Show();
                    //Common.fingerPrintAuthority = "";

                    //Frm_Login.Instance.SetPassCode();
                }
                Thread.Sleep(200);
                Application.DoEvents();
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Home.Instance.Show();
            Frm_Statistics.Instance.Hide();

            isHomeFormShow = true;
            isSettingFormShow = false;
            isStatisticsFromShow = false;
            isVisionFromshow = false;
            isLoginFormshow = false;

            RegiserLockProcess();
        }

        #endregion

        #region 事件
        private void Frm_Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            MachineStatusManager.CurrentMachineStatus = MachineStatus.Quit;
            if (MVCameraList.Count() != 0)
            {
                MVCameraList.Close("TrayLoactionCCD");
                MVCameraList.Close("LoadingLocationCCD1");
                MVCameraList.Close("UpMeasureCCD");
                MVCameraList.Close("UnloadingTrayLoactionCCD");
            }

            PublicMethod.StopMachine();
            Process.GetCurrentProcess().Kill();
            Application.Exit();
        }
        #endregion

        #region UI

        private void ucBtnImg_MouseEffected(object sender, EventArgs e)
        {
            var btn = sender as HZH_Controls.Controls.UCBtnExt;
            btn.FillColor = Color.FromArgb(238, 238, 237);
        }

        private void ucBtnImg_MouseEffecting(object sender, EventArgs e)
        {
            var btn = sender as HZH_Controls.Controls.UCBtnExt;
            btn.FillColor = Color.FromArgb(174, 218, 151);
        }


        #endregion

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                isBlockModel = true;
            }
            else
            {
                isBlockModel = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Frm_InitItemStatu.Instance.Show(this);
        }

        private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            Dlg_InputMsgComfirm inputMsgComfirmDlg = new Dlg_InputMsgComfirm(Configuration.language == Configuration.Language.Chinese ? "确认框" : "Confirm Dialog", Configuration.language == Configuration.Language.Chinese ? "确认关闭软件？" : "Close the Software Now?");
            if (inputMsgComfirmDlg.ShowDialog(this) == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
            else
            {
                DateTime startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").ToString());
                int timeCount = (endTime - startTime).Seconds;
                AlarmInfo alarmInfo = new AlarmInfo()
                {
                    StartTime = startTime,
                    EndTime = endTime,
                    TimeCount = timeCount,
                    Type = "软件关闭",
                    Description = "手动关闭软件，关闭原因：" + inputMsgComfirmDlg.msg
                };

                AlarmInfoServices AlarmInfoServices = new AlarmInfoServices();
                AlarmInfoServices.Add(alarmInfo);
            }
        }

        private void settingToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //if (Common.username == "Apple" || Common.username == "superadmin"
            //        || Common.username == "EN"
            //        || Common.username == "Battery QM")
            {
                if (e.ClickedItem == tsmi_MotionConfig)//运动参数配置
                {
                    Frm_MachineConfig.Instance.Show();
                }
            }
            //else
            //{
            //    MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}

        }

        private void tsmi_OpenProject_Click(object sender, EventArgs e)
        {
            if (username == "Apple" || username == "superadmin"
                      || username == "EN"
                      || username == "Battery QM")
            {
                if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Homing
                    || MachineStatusManager.CurrentMachineStatus == MachineStatus.Running
                    )
                {
                    MessageBox.Show("设备正在运行，请先停止！");
                }
                OpenFileDialog mDialog = new OpenFileDialog();
                mDialog.Filter = "(*.gra)|*.gra";
                if (DialogResult.OK == mDialog.ShowDialog())
                {

                    ProjectName = mDialog.SafeFileName.Split('.')[0];
                    MachineDataManager.ProjectName = ProjectName;
                    ucBtnExt_MachineInfo.BtnText = ProjectName;
                    MachineDataManager.Instance.Init();
                    MachineDataManager.LoadFromFile();

                    Frm_MachineConfig.Instance.ReloadProject();
                    if (ProjectName == "Bolck")
                    {
                        Frm_Home.Instance.RefreshHomeUI(ProjectName);
                    }
                    else
                    {
                        Frm_Home.Instance.RefreshHomeUI("Product");
                    }
                    Frm_Home.Instance.ReadHistoryData();
                    Machine.MachineResourceInit();
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

        }

        private void tsmi_NewProject_Click(object sender, EventArgs e)
        {
            if (username == "Apple" || username == "superadmin"
                     || username == "EN"
                     || username == "Battery QM")
            {
                if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Homing
                      || MachineStatusManager.CurrentMachineStatus == MachineStatus.Running
                      )
                {
                    MessageBox.Show("设备正在运行，请先停止！");
                }
                Dlg_SelectProject selectProjectDialog = new Dlg_SelectProject();
                selectProjectDialog.Title = "新建项目";
                if (selectProjectDialog.ShowDialog(Frm_Home.Instance) != DialogResult.OK)
                {
                    return;
                }

                MachineDataManager.ProjectName = ProjectName;
                ucBtnExt_MachineInfo.BtnText = ProjectName;

                MachineDataManager.Instance.Init();
                MachineDataManager.LoadFromFile();

                Frm_MachineConfig.Instance.ReloadProject();
                if (ProjectName == "Bolck")
                {
                    Frm_Home.Instance.RefreshHomeUI(ProjectName);
                }
                else
                {
                    Frm_Home.Instance.RefreshHomeUI("Product");
                }

                Frm_Home.Instance.ReadHistoryData();
                Machine.MachineResourceInit();
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }




        public class UserOptionCheckBFMessage : IMessageFilter
        {
            public bool RegiserLockFlag = true;
            public int nUserOptionsCount = 0;

            public bool PreFilterMessage(ref Message m)
            {
                //检测鼠标或者键盘的消息
                if (m.Msg == 0x0200 || m.Msg == 0x0201 || m.Msg == 0x0204 || m.Msg == 0x0207)
                {
                    nUserOptionsCount = 0;
                }
                return false;
            }
        }

        private void btn_ClearMachine_Click(object sender, EventArgs e)
        {

        }

        public void UpdateStartOnce(bool? 启动一次, string msg = "")
        {
            if (Common.启动一次 == false)
            {
                btn_StartOnce.BackColor = Color.Gray;
            }
            else if (Common.启动一次 == true)
            {
                btn_StartOnce.BackColor = Color.Green;
            }
            else
            {
                btn_StartOnce.BackColor = Color.Transparent;
            }

            if (!string.IsNullOrEmpty(msg))
            {
                btn_StartOnce.Text = "启动一次" + msg;
            }
            else
            {
                btn_StartOnce.Text = "启动一次";
            }
        }
        private void btn_StartOnce_Click(object sender, EventArgs e)
        {
            if (启动一次 == false)
            {
                启动一次 = true;
                UpdateStartOnce(启动一次);
            }
            else
            {
                启动一次 = false;
                UpdateStartOnce(启动一次);
            }
        }
        private void btn_DT_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定[是否进入维护模式]", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                Dlg_ManualDownBegin.Instance.alarmInfo = new AlarmInfo() { StartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) };
                Dlg_ManualDownBegin.Instance.Show();
            }
            else
            {

            }
        }


        private void ProTypeListItemsInit()
        {
            tscb_ProTypeList.Items.Clear();
            foreach (var item in ProductTypeMeasureItemEnableList)
            {
                tscb_ProTypeList.Items.Add(item.ProductType);
            }
            tscb_ProTypeList.SelectedItem = CurProType;
            lbl_CurProType.Text = CurProType;

            CurProTypeMeasureItems = ProductTypeMeasureItemEnableList.Find(x => x.ProductType.Equals(CurProType));
            if (CurProTypeMeasureItems == null)
            {
                AppendUiLog.Log($"选择当前产品类型异常", LogType.Error);
            }
        }
        bool isFrist = true;
        private void tscb_ProTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Initialized
                || MachineStatusManager.CurrentMachineStatus == MachineStatus.Ready)
            {
                if (tscb_ProTypeList.SelectedItem.ToString() != CurProType)
                {
                    toolStripComboBox1.Items.Clear();
                    if (tscb_ProTypeList.SelectedItem.ToString() == "Product")
                    {
                        whichBlock = -1;
                        toolStripComboBox1.Items.Add("-1");
                        toolStripComboBox1.SelectedItem = "-1";
                        toolStripComboBox1.Enabled = false;

                    }
                    else
                    {
                        whichBlock = 0;
                        toolStripComboBox1.Text = "0";
                        toolStripComboBox1.Items.Add("0");
                        toolStripComboBox1.Items.Add("1");
                        toolStripComboBox1.Items.Add("2");
                        toolStripComboBox1.Enabled = true;
                    }
                    CurProType = tscb_ProTypeList.SelectedItem.ToString();
                    lbl_CurProType.Text = CurProType;
                    if (CurProType == "Product")
                    {
                        Frm_Setting.Instance.DgvBindSource();
                    }

                    var ret = this.Invoke(new Action(() =>
                    {
                        PublicMethod.ChangeProjectExvent();
                    }));
                    CurProTypeMeasureItems = ProductTypeMeasureItemEnableList.Find(x => x.ProductType.Equals(CurProType));
                    if (CurProTypeMeasureItems == null)
                    {
                        AppendUiLog.Log($"选择当前产品类型异常", LogType.Error);
                    }
                    Frm_Home.Instance.RefreshHomeUI(CurProType);
                    PublicMethod.WriteCurProTypeIni(CurProType);
                }
                PublicMethod.ReadCSVFile();
            }
            else
            {

                if (isFrist == false)
                {
                    MessageBox.Show("禁止切换产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    isFrist = false;
                }

            }
        }


        private void UpdateProTypeMeasureItemsEnable(List<ProductTypeMeasureItemEnable> productTypeMeasureItemEnables)
        {
            if (ProductTypeMeasureItemEnableList.Count > 0)
            {
                bool isContainCurProType = false;
                foreach (var item in ProductTypeMeasureItemEnableList)
                {
                    if (item.ProductType.Equals(CurProType))
                        isContainCurProType |= true;
                }
                if (isContainCurProType)
                {
                    ProTypeListItemsInit();
                }
                else
                {
                    tscb_ProTypeList.Items.Clear();
                    foreach (var item in ProductTypeMeasureItemEnableList)
                    {
                        tscb_ProTypeList.Items.Add(item.ProductType);
                    }
                    tscb_ProTypeList.SelectedIndex = 0;
                    CurProType = tscb_ProTypeList.SelectedItem.ToString();
                    lbl_CurProType.Text = CurProType;

                    CurProTypeMeasureItems = ProductTypeMeasureItemEnableList.Find(x => x.ProductType.Equals(CurProType));
                    if (CurProTypeMeasureItems == null)
                    {
                        AppendUiLog.Log($"选择当前产品类型异常", LogType.Error);
                    }
                }
            }
            else
            {
                //todo
            }
        }

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (toolStripComboBox1.Text == "-1"
                || tscb_ProTypeList.Text == "Product")
            {
                return;
            }
            if (toolStripComboBox1.Text == "0")
            {
                whichBlock = 0;

            }
            if (toolStripComboBox1.Text == "1")
            {
                whichBlock = 1;
            }
            if (toolStripComboBox1.Text == "2")
            {
                whichBlock = 2;
            }
            if (toolStripComboBox1.Text == "-1")
            {
                Frm_Home.Instance.RefreshHomeUI("Product");
            }
            else
            {
                Frm_Home.Instance.RefreshHomeUI("Block");
            }

            Frm_Setting.Instance.DgvBindSource();
        }
    }
}